package com.aube.video;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import com.aube.BaseFragmentActivity;
import com.aube.R;
import com.aube.activity.ResolutionHelper;
import com.aube.video.ad.VideoAdHelper;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.utils.AppUtil;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.StorageUtil;
import com.huyn.baseframework.utils.UserUtil;
import com.huyn.baseframework.utils.Utils;

/**
 * Created by huyaonan on 16/3/16.
 */
public class PlayActivity extends BaseFragmentActivity {

    public static final String TAG = "PlayActivity";

    public static final String CHANNEL_ITEM = "CHANNEL_ITEM";
    public static final String CATEGORY_ITEM = "CATEGORY_ITEM";

    private ChannelDetail mChannel;
    private Category mCategory;

    private BroadcastReceiver brr;

    private VideoAdHelper mVideoAdHelper;

    private PlayerProxy mPlayerProxy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.keepScreenOn(this);
        AppUtil.setTranslucentStatus(this, true);

        Utils.Log(TAG, "oncreate====================================");

        mChannel = (ChannelDetail) getIntent().getSerializableExtra(CHANNEL_ITEM);
        mCategory = (Category) getIntent().getSerializableExtra(CATEGORY_ITEM);
        if(mChannel == null) {
            finish();
            return;
        }

        setContentView(R.layout.activity_aube_play);

        //display AD
        displayAD();

        mPlayerProxy = new PlayerProxy(this, mChannel, mCategory);
        mPlayerProxy.init();

        registBrr();
        setVolume();
    }

    /**
     * 展示开屏广告
     */
    private void displayAD() {
//        mVideoAdHelper = new VideoAdHelper(this, new VideoAdHelper.IAdStateListener() {
//            @Override
//            public void onFinished() {
//                if(mPlayerProxy != null)
//                    mPlayerProxy.onAdFinished();
//            }
//
//            @Override
//            public void onPauseAdFinished() {
//            }
//        });
//        mVideoAdHelper.fetchAndShowAd(this);
    }

    /**
     * 开屏广告是否在展示当中
     * @return
     */
    public boolean isAdPlaying() {
//        if(mVideoAdHelper != null) {
//            boolean isVideoShowing = mVideoAdHelper.isAdShowing();
//            return isVideoShowing;
//        }
        return false;
    }

    /**
     * 清除广告
     */
    public void hidePauseAD() {
//        if(mVideoAdHelper != null)
//            mVideoAdHelper.clearAd();
    }

    /**
     * 展示暂停广告
     */
    public void showPauseAD() {
//        if(mVideoAdHelper != null)
//            mVideoAdHelper.showAd();
    }

    private void setVolume() {
        //音量控制,初始化定义
        AudioManager mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        //最大音量
        int maxVolume =mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        if(Constant.DEBUG) {
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume / 4, 0);
        } else {
            //当前音量
            int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (currentVolume < maxVolume / 2)
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume / 2, 0);
        }
    }

    private void registBrr() {
        brr = new BroadcastReceiver() {

            @Override
            public void onReceive(Context arg0, Intent intent) {
                if (UserUtil.LOGIN_SUCCESS.equalsIgnoreCase(intent.getAction())) {
                    if(mPlayerProxy != null)
                        mPlayerProxy.toWriteDanmu();
                }
            }
        };

        IntentFilter iff = new IntentFilter();
        iff.addAction(UserUtil.LOGIN_SUCCESS);
        registerReceiver(brr, iff);
    }

    @Override
    public void onResume() {
        super.onResume();
        Utils.Log(TAG, "onresume==============================");
        if(mPlayerProxy != null)
            mPlayerProxy.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        Utils.Log(TAG, "onpause==============================");
        if(mPlayerProxy != null)
            mPlayerProxy.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Utils.Log(TAG, "ondestroy==============================");
        if(mPlayerProxy != null)
            mPlayerProxy.onDestroy();
        if(brr != null)
            unregisterReceiver(brr);
    }

    @Override
    public View getBaseRootView() {
        return findViewById(R.id.root);
    }

    @Override
    public boolean dismissLoginHelper() {
        if(mPlayerProxy != null)
            mPlayerProxy.resumeFromLogin();
        return super.dismissLoginHelper();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Utils.Log(TAG, "onkeydown==============================");
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            if(onBackKeyPressed(keyCode, event))
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected boolean onBackKeyPressed(int keyCode, KeyEvent event) {
        try {
            if(keyCodeBackPressed(keyCode, event))
                return true;

            if(mPlayerProxy.onBackPressed())
                return true;

            ResolutionHelper.getInstance().updateCode(0);

            HttpRequestLoader.getInstance(this).cancelAllRequest();

            finish();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Utils.Log(TAG, "restore==============================");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Utils.Log(TAG, "save==============================");
    }

    /**
     * 当statusbar被下拉的时候会调用
     * 当锁屏/按home键也会被调用,但在最后
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        if(mPlayerProxy != null)
            mPlayerProxy.onWindowFocusChanged(hasFocus);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //continue
            if(mPlayerProxy != null)
                mPlayerProxy.continueAfterPermissionGet();
        } else {
            //授权被拒绝
        }
    }

    /**
     * Checks whether it is necessary to ask for permission to read storage. If necessary, it also
     * requests permission.
     *
     * @return true if a permission request is made. False if it is not necessary.
     */
    @TargetApi(23)
    protected boolean shouldRequestPermission() {
        if (requiresPermission()) {
            requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            return true;
        } else {
            return false;
        }
    }

    @TargetApi(23)
    private boolean requiresPermission() {
        return StorageUtil.SDK_INT >= 23
                && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //do nothing
        Utils.sysout("********************onConfigurationChanged");
    }
}
